using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace RSSRadio
{
	static class StringUtil
	{
		/// <summary>
		/// Removes CDATA xml tags enclosing a string
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string StripXmlCDATATags(string str)
		{
			if (str.StartsWith("<![CDATA[") && str.EndsWith("]]>"))
				str = str.Substring(9, str.Length - 12);

			return str;
		}

		/// <summary>
		/// Chops a phrase or sentence down to the specified length and appends
		/// '...'. May leave partial words, e.g. "The ball was re..."
		/// </summary>
		public static string ChopPhraseDownToLength(string str, int maxLength)
		{
			if (str.Length > maxLength)
			{
                str = str.Substring(0, Math.Max(0, maxLength - 3)) + "...";

				//str = str.Substring(0, str.LastIndexOf(' ')) + "...";
			}
			return str;
		}

		public static string GetMediaFileName(string url)
		{
			char[] delimeters = { '/' };
			string[] splitRequest = url.Split(delimeters);
			string fileName = splitRequest[splitRequest.Length - 1];

			// if file name doesn't have a three char extension, fix it up
			//		this is a workaround for urls like "example.com/file.mp3?param=1&param2=2"
			if (fileName.Length > 4 && fileName[fileName.Length - 4] != '.')
			{
				// if fileName contains ".mp3"
				if (fileName.IndexOf(".mp3") != -1)
					fileName = fileName.Substring(0, fileName.IndexOf(".mp3") + 4);
			}

			return fileName;
		}

		/// <summary>
		/// Removes HTML tags from a string.
		/// </summary>
		/// <remarks>
		/// Author: Jorn Baayen
		/// Source: Banshee Plugins > StringUtils.cs; http://banshee-project.org/
		/// </remarks>
		public static string StripHTML (string s)
		{
			if (s == null)
				return "";
			Regex r = new Regex("<[^>]+>");
			return r.Replace(s, "");
		}

		public static string StripNewLines(string str)
		{
			return str.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
		}
	}
}
